<?php

namespace App\Api\Controllers;

/* use App\Http\Controllers\Controller; */
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Helper\Utils\TimeUtil;
use App\Api\Services\QuotationNoService;
use App\Api\Models\QuotationNoModel;
use App\Http\Controllers\Api\BaseController;
use App\Api\Models\QuotationGoodsModel;
use App\Api\Models\AdminModel;
class QuotationNoController extends BaseController
{
    /**
     * 添加报价单
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'offer_company'     =>'string',//报价公司
            'customer_name'     =>'string',//客户名称
            'customer_phone'    =>'string',//客户联系电话
            'customer_address'  =>'string',//客户地址                   
            'total_cost'        =>'string',//本单合计
            'down_payment'      =>'string',//预付定金
            'preferential_price'=>'string',//优惠价
            'balance_payment'   =>'string',//尾款        
            'announcements'     =>'string',//注意事项
            'tabel_time'        =>'string',//出表时间
            'total_cost'        =>'numeric|min:0',//本单合计
            'down_payment'      =>'numeric|min:0',//预付定金
            'preferential_price'=>'numeric|min:0',//优惠价
            'balance_payment'   =>'numeric|min:0',//尾款 
            
        ],[
            'total_cost.numeric'        => '本单合计只能为数字',
            'total_cost.min'            => '本单合计最小只能为0',           
            'down_payment.numeric'      => '预付定金只能为数字',
            'down_payment.min'          => '预付定金最小只能为0',
            'preferential_price.numeric'=> '优惠价只能为数字',
            'preferential_price.min'    => '优惠价最小只能为0',
            'balance_payment.numeric'   => '尾款只能为数字',
            'balance_payment.min'       => '尾款最小只能为0',
    
        ]);
    
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        //开启事务
       DB::beginTransaction();       
        try{
            //报价单
            $dData = $data;        
               if(empty($dData['offer_company'])){
                   
                   $uInfo = AdminModel::select('company_name')->where('id', $this->getMainUserId())->first();
                   
                   if(!empty($uInfo['company_name'])){//主账号信息里的公司名称填写为报价单公司
                       
                       $dData['offer_company']=$uInfo['company_name'];
                   }
               }            
            $dData['created_at']    = time();
            $dData['user_id']       = $this->getUserId();
            $dData['main_id']       = $this->getMainUserId();
            
            if(empty($dData['quotation_no'])){
                
             $dData['quotation_no']  = $this->getMainUserId().TimeUtil::getMillisecond();//报价单号
            }
            $quotation_id           = QuotationNoService::add($dData);
            //$data['goods_info']='[{"name":"苹果","type_name":"红","product_unit":"件","price":"5.6","num":"10","remark":"好吃的很","serial_number":11,"goods_label":"掌上网络","goods_img":"214124.png"},{"name":"水梨","type_name":"黄","product_unit":"件","price":"3.6","num":"8","remark":"好吃的很","serial_number":22,"goods_label":"掌上网络02","goods_img":"56757.png"}]';
            //商品详细添加
            if(isset($data['goods_info']) && !empty($data['goods_info'])){
    
                $goodsInfo = json_decode($data['goods_info'],true);
                 if(is_array($goodsInfo)){
                    foreach ($goodsInfo as &$value){
        
                        $value['created_at'] = time();
                        $value['quotation_id'] = $quotation_id;
                        $value['user_id']     = $this->getUserId();
                        $value['main_id']     = $this->getMainUserId();
                    }
        
                    QuotationGoodsModel::insert($goodsInfo);
                 }
            }
             
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加报价单');
        }
         
    }
    
    /**
     * 删除报价单信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//报价单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
        $id_data = [];
        $id_arr  = explode(',',$data['ids']);
        /* $condition['id']      = $data['quotation_id']; */
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
    
        /* $info = QuotationNoService::getQuotationNoInfo($condition); */
        $list = QuotationNoModel::select('id')->where($condition)->whereIn('id',$id_arr)->get()->toArray();
        
        if(!empty($list)){
    
            /* $bool = QuotationNoService::delete($condition); */
            
            foreach ($list as $k=>$v){
            
                $id_data[]=$v['id'];
            }
            $bool = QuotationNoModel::where($condition)->whereIn('id',$id_data)->delete();
            
            if($bool){
    
                QuotationGoodsModel::where($condition)->whereIn('quotation_id',$id_data)->delete();
    
                return $this->success();
                 
            }else{
                return $this->fail('','删除失败');
            }
        }
        return $this->fail('','报价单，不存在！');
    }
    
    /**
     * 修改报价单
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'quotation_id'      =>'required|integer',//报价单id
             'offer_company'    =>'string',//报价公司
            'customer_name'     =>'string',//客户名称
            'customer_phone'    =>'string',//客户联系电话
            'customer_address'  =>'string',//客户地址           
            'deliver_person'    =>'string',//发货人
            'order_time'        =>'string',//下单时间
            'total_cost'        =>'string',//本单合计
            'down_payment'      =>'string',//预付定金
            'preferential_price'=>'string',//优惠价
            'balance_payment'   =>'string',//尾款        
            'announcements'     =>'string',//注意事项
            'tabel_time'        =>'string',//出表时间
            'total_cost'        =>'numeric|min:0',//本单合计
            'down_payment'      =>'numeric|min:0',//预付定金
            'preferential_price'=>'numeric|min:0',//优惠价
            'balance_payment'   =>'numeric|min:0',//尾款 
            
        ],[
            'total_cost.numeric'        => '本单合计只能为数字',
            'total_cost.min'            => '本单合计最小只能为0',           
            'down_payment.numeric'      => '预付定金只能为数字',
            'down_payment.min'          => '预付定金最小只能为0',
            'preferential_price.numeric'=> '优惠价只能为数字',
            'preferential_price.min'    => '优惠价最小只能为0',
            'balance_payment.numeric'   => '尾款只能为数字',
            'balance_payment.min'       => '尾款最小只能为0',
    
        ]);
    
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $info = QuotationNoService::getQuotationNoInfo(['id'=> $data['quotation_id']]);
         
        if(empty($info)){
             
            return $this->fail('','报价单号,不存在！');
        }
        //开启事务
        DB::beginTransaction();
        try{
            //报价单
            $updData = $data;
            
            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['quotation_id'];
            //$updData['goods_info']='[{"goods_id":1,"name":"葡萄11","type_name":"紫11","product_unit":"红富士11","price":"5.611","num":"1011","remark":"好吃的很的很","serial_number":11,"goods_label":"掌上网络0333","goods_img":"111111.png"},{"goods_id":2,"name":"水梨2222","type_name":"黄22","product_unit":"砀山梨22","price":"3.6","num":"8","remark":"好吃的很的很","serial_number":22,"goods_label":"掌上网络03333","goods_img":"22222.png"},{"name":"水梨8888","type_name":"黄888","product_unit":"砀山梨888","price":"3.6","num":"8","remark":"好吃的很的很","serial_number":22,"goods_label":"掌上网络44444","goods_img":"3333.png"}]';
    
            if(isset($updData['goods_info']) && !empty($updData['goods_info'])){
    
                $goodsInfo = json_decode($updData['goods_info'],true);
                
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as $value){//更新商品信息
                        //更新
                        if(isset($value['goods_id'])){
        
                            $dCondition['id'] = $value['goods_id'];
        
                            unset($value['goods_id']);
        
                            QuotationGoodsModel::where($dCondition)->update($value);
                        }else{//添加
        
                            $value['created_at']  = time();
                            $value['user_id']     = $this->getUserId();
                            $value['main_id']     = $this->getMainUserId();                        
                            $value['quotation_id'] = $updData['quotation_id'];
                               
                            QuotationGoodsModel::insert($value);
                        }
                    }
                }
                unset($updData['goods_info']); unset($updData['quotation_id']);
            }
            
            $updData['updated_at'] = time();
            $quotation_id = QuotationNoService::update($condition,$updData);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改报价单');
        }
    
    }
    
    /**
     * 报价单信息
     * @param quotation_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'quotation_id'       =>'required|integer',//报价单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['quotation_id'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
    
        $info = QuotationNoService::getQuotationNoInfo($condition);
        $list = $info;
        if(!empty($info)){
    
            $list['goods_list']= QuotationGoodsModel::where(['quotation_id'=>$info['id']])->get();
    
        }
    
        return $this->success($list);
    }
    
    /**
     * 报价单列表
     */
    public function QuotationNoList(Request $request){
    
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $id_arr01 = [];
        $id_arr02 = [];
        $quotation_id_arr = [];
    
        $keyword = empty($data['keyword'])?'':$data['keyword'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        if(!empty($keyword)){
    
            $goodsList = QuotationGoodsModel::select('quotation_id')
            ->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('name', 'like', '%'.$keyword.'%');
                $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
            })
            ->orderBy('quotation_id','DESC')
            ->get()->toArray();
    
            if(!empty($goodsList)){
    
                foreach ($goodsList as $k=>$v){
    
                    $id_arr01[$k] = $v['quotation_id'];    
                }
            }
    
            $list = QuotationNoModel::select('id')->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('quotation_no', 'like', '%'.$keyword.'%');
                $query->orWhere('customer_name', 'like', '%'.$keyword.'%');
                $query->orWhere('customer_phone', 'like', '%'.$keyword.'%');
                $query->orWhere('customer_address', 'like', '%'.$keyword.'%');
            })->orderBy('id','desc')
            ->get()->toArray();
           
            if(!empty($list)){
    
                foreach ($list as $k=>$v){
    
                    $id_arr02[$k] = $v['id'];
                }
            }
    
            $quotation_id_arr = array_unique(array_merge($id_arr01,$id_arr02));
           
            if(empty($quotation_id_arr)){
                
                $quotation_id_arr[0] ="0";
            }           
        }
    
        $list = QuotationNoService::getList($condition,$quotation_id_arr,$data['pageSize'],$data['currentPage']);
    
        if(!empty($list['data'])){
    
            foreach ($list['data'] as &$value){
    
                $query = QuotationGoodsModel::where('quotation_id',$value['id']);
    
                if(!empty($id_arr01)){
    
                    $query->where(function($query) use ($keyword) {
                        $query->orWhere('name', 'like', '%'.$keyword.'%');
                        $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                        $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
                    });
                }
                $value['goods_info'] =  $query->get();
            }
        }
        return $this->success($list);
    
    }
    /**
     * 上传商品图片（单个）
     * @param goods_img 商品图片
     */
    public function uploadGoodsImg(Request $request){
        
        if(!empty($goods_img_file = $request->file('goods_img'))){
            
            $res = SELF::handlePicFormat($goods_img_file, '商品图片格式，不正确！');
        
            if(!empty($res)){
        
                return response()->json($res);
            }
            if($goods_img_file->isValid()){
                 
                $img_path = $goods_img_file->store('goods-img/'.date('Y').'-'.date('m').'-'.date('d'));
                $path = '/uploads/'.$img_path;       
                return response()->json(['code'=>0,'msg'=>'success','data'=>['path'=>$path]]);
                 
            }else{
                 
                return response()->json(['code'=>1,'msg'=>'上传失败','data'=>'']);
            }
             
        }else{
            return response()->json(['code'=>1,'msg'=>'请选择商品图片','data'=>'']);
        
        }
        
    }
    
    /**
     * 处理图片格式
     */
    static public function handlePicFormat($files,$msg){

        $pic_format = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';
    
    
        $ext = $files->extension();
    
        $ext = strtolower($ext);
    
       $pic_format = explode(',',$pic_format);
         
        if (!in_array($ext, $pic_format)) {
             
            return ['code' => 1,'msg' => $msg,'data' => ''];die;
        }
         
    }
   
}
